/*
 * Copyright (C) 2021 Fastjrun, Inc. All Rights Reserved.
 */
package com.fastjrun.test.common;

import org.testng.collections.Maps;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class ParamSingleton {


    public Map<String, Object> getPropParams() {
        return propParams;
    }

    private Map<String, Object> propParams = Maps.newHashMap();


    private volatile static ParamSingleton INSTANCE = null;


    private static int count = 0;

    private ParamSingleton(String envName) {
        if (this.propParams == null || this.propParams.size() == 0) {
            try {
                this.propParams = initParamFromYaml("/testdata/" + envName + ".yaml");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static final ParamSingleton getInstance(String envName) {
        if (INSTANCE == null) {
            synchronized (ParamSingleton.class) {
                if (INSTANCE == null) {
                    System.out.println("count=" + count++);
                    INSTANCE = new ParamSingleton(envName);
                }
            }
        }
        return INSTANCE;
    }

    public Map<String, Object> loadParam() {

        return this.propParams;
    }


    private Map<String, Object> initParamFromYaml(String yamlFileInClassPath) throws IOException {
        Yaml yaml = new Yaml();
        System.out.println(yamlFileInClassPath);
        InputStream inParam = this.getClass().getResourceAsStream(yamlFileInClassPath);
        Map<String, Object> map = yaml.loadAs(inParam, Map.class);

        inParam.close();
        return map;

    }

}
